package com.think.cloud.thinkshop.mall.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.think.common.core.exception.ServiceException;
import com.think.common.core.exception.util.ServiceExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author zkthink
 * @apiNote 17track物流查询
 **/
@Component
@Slf4j
public class Logistics17TrackClient {
    @Value("${17track.secret}")
    private String secret;

    private static final String BASE_URL = "https://api.17track.net/track/v2.2";
    // 注册物流单号
    private static final String REGISTER_URL = BASE_URL + "/register";


    /**
     * 注册单号
     *
     * @param trackNumber 物流单号
     * @return /
     */

    public String register(String trackNumber) {
        JSONObject entries = new JSONObject();
        entries.set("number", trackNumber);
        JSONArray jsonArray = new JSONArray(entries);
        String resBody = HttpRequest
                .post(REGISTER_URL)
                .body(jsonArray.toString())
                .header("Content-Type", "application/json")
                .header("17token", secret)
                .execute()
                .body();
        log.info("registerTrackNumber trackNumber:{},param:{},resBody:{}", trackNumber,jsonArray, resBody);
        JSONObject resObj = new JSONObject(resBody);
        Integer code = resObj.getInt("code");
        if(code == 0){
            JSONObject data = resObj.getJSONObject("data");
            JSONArray errors = data.getJSONArray("errors");
            if(ObjectUtil.isNotNull(errors)){
                JSONObject error1 = new JSONObject(errors.get(0));
                if(error1.getInt("code") != 0){
                    throw new ServiceException("物流单号注册失败 " + error1.getStr("message"));
                }
            }
        }else {
            throw new ServiceException("物流单号注册失败");
        }
        return resBody;
    }
}
